import time, cv
import socket
import Image
import StringIO

capture = cv.CaptureFromCAM(0)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 640)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 480)

HOST, PORT = "192.168.1.100", 3220
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))

while True:
    img = cv.QueryFrame(capture)
    pi = Image.fromstring("RGB", cv.GetSize(img), img.tostring())
    buf = StringIO.StringIO()
    pi.save(buf, format="JPEG")
    jpeg = buf.getvalue()
    buf.close()
    transfer = jpeg.replace("\n", "\-n")
    sock.sendall(transfer + "\n")
    time.sleep(0.01)

sock.close()

'''
import time, cv
import cv2
import socket
import numpy as np
import Image
import StringIO

capture = cv2.VideoCapture(0)
# capture = cv.CaptureFromCAM(0)
# cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 640)
# cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 480)

HOST, PORT = "192.168.1.100", 3220
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
img = np.zeros((480, 640, 3), dtype=np.uint8)

while True:
    capture.read(img)
    # img = cv.QueryFrame(capture)
    print img.shape[0:2]
    pi = Image.fromstring("RGB", img.shape[0:2], img.tostring())
    buf = StringIO.StringIO()
    pi.save(buf, format="JPEG", )
    jpeg = buf.getvalue()
    buf.close()
    transfer = jpeg.replace("\n", "\-n")
    sock.sendall(transfer + "\n")
    cv2.imshow("src", img);
    cv2.waitKey(20)
    # time.sleep(0.03)

sock.close()
'''